<?php
namespace app\admin\middleware;

use think\facade\Session;
use app\admin\model\WorkerDepartment as WDM;
use app\common\exception\AdminException;

class Authentication
{
    /**
     * @var array 不需要登陆判断的节点
     */
    protected $ignoreLogin = ['index_index', 'index_login'];

    /**
     * @var array 不需要进行权限判断
     */
    protected $ignoreAuth = ['index_welcome', 'index_main', 'index_logout', 'index_uploader', 'index_uploaded'];

    /**
     * @param $request
     * @param \Closure $next
     */
    public function handle($request, \Closure $next)
    {
        $node = $request->controller() . '_' . $request->action();

        //该节点可以不需要登陆 不会鉴权
        if ( $this->ignoreLogins( strtolower($node) ) ) {
            return $next($request);
        }

        $workerId = Session::get('admin.worker.id');
        if ( !$workerId ) return redirect( url('/admin') );

        if ( $this->ignoreAuths(strtolower($node), $workerId)) {
            return $next($request);
        }

        if ( !$this->hasAuthVisiter(strtolower($node)) ) {
            throw new AdminException('您无权限访问');
        }

        bind('worker', function(){ return Session::all()['admin']['worker']; });
        return $next($request);
    }

    /**
     * [hasAuthVisiter 检测用户是否有访问当前节点的权限]
     * @param  [type]  $node [description]
     * @return boolean       [description]
     */
    public function hasAuthVisiter($node)
    {
        $depart_id  = Session::get('admin.worker.depart_id');
        $departInfo = WDM::find($depart_id);
        if (!$depart_id || !$departInfo) {
            return false;
        }
        return in_array($node, $departInfo['node_indexs']);
    }

    /**
     * 判断节点是否在免登录接口
     * @param $node
     * @return bool
     */
    public function ignoreLogins($node)
    {
        return in_array($node, $this->ignoreLogin);
    }

    /**
     * 判断节点是否在免鉴权接口
     * @param $node
     * @param $workerId
     * @return bool
     */
    public function ignoreAuths($node, $workerId)
    {
        return in_array($node, $this->ignoreAuth) || $workerId === 1;
    }
}
